package com.galina.notebook.dao;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public abstract class GenericDaoImpl<T> implements GenericDao<T> {

	@PersistenceContext(unitName = "notebook")
	protected EntityManager em;
	
    private Class< T > type;

    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public GenericDaoImpl() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        type = (Class) pt.getActualTypeArguments()[0];
    }
    
	@Override
	public T create(T t) {
		 this.em.persist(t);
	     return t;	
	}

	@Override
	public void delete(Object id) {
		this.em.remove(em.getReference(type, id));
		
	}

	@Override
	public T update(T t) {
		return this.em.merge(t); 
	}

	@Override
	public T find(Object id) {
		 return (T) this.em.find(type, id);
	}

	@SuppressWarnings("rawtypes")
	public List executeQuery(String queryString){
		try {
			Query query = em.createQuery(queryString);
			return query.getResultList();
		} catch (NoResultException ex) {
			return Collections.emptyList();
		}
	}
}
